import threading, os, time, sys, requests, traceback
parent_path = os.path.abspath(os.path.join(__file__, *(['..'] * 4)))
sys.path.insert(0, parent_path)

from core.utils.logger import logging
class Keeper():
    """ 间隔轮询进程是否存在, 如果不存在则重启它
    args:
        thread_name: 进程名
        sh_file_path: 需要启动的 shell 脚本文件地址
        stride_time: 轮询间隔, 默认5分钟

    """
    def __init__(self, thread_name, sh_file_path, stride_time=5*60):
        self.thread_name = thread_name
        self.run_file = sh_file_path
        self.stride_time = stride_time
        self.thread = None
        self.status = 0 # 0: standby, 1: running

    def close(self):
        """
        关闭keeper轮询并且将被监控的进程也关闭
        """
        logging.info("|INFO: close keeper.|")
        self.status = 0
        shell_ret = os.popen("ps -ef |grep {}".format(self.thread_name))
        for line in shell_ret.readlines():
            if "grep" in line:
                continue
            else:
                line_split = [x for x in line.split(" ") if x!=""]
                pid = line_split[1]
                shell_ret = os.popen("kill {}".format(pid))

    def run(self):
        self.status = 1
        while self.status == 1:
            # shell_ret = os.popen("ps -ef |grep {}".format(self.thread_name))
            # running_threads = []
            # for line in shell_ret.readlines():
            #     if "grep" in line:
            #         continue
            #     else:
            #         running_threads.append(line)
            ret = self.check_running()
            if not ret : # 进程不存在, 重启
                logging.info("|INFO: can't find {}, restart|".format(self.thread_name))
                os.system('chmod +x {}'.format(self.run_file))
                shell_ret = os.popen("sh "+self.run_file)

            time.sleep(self.stride_time)

    def check_running(self):
        """
        返回当前守护的目标进程是否存在
        """
        shell_ret = os.popen("ps -ef |grep {}".format(self.thread_name))
        for line in shell_ret.readlines():
            if "grep" in line:
                continue
            else:
                return True
        return False
    
    def start(self):
        logging.info("|INFO: start keeper to keep {}|".format(self.run_file))
        self.thread = threading.Thread(target=self.run)
        self.thread.start()
        
def _http_post(resp_url, json_data):
    try:
        logging.info("|post data to {}|".format(resp_url))
        requests.post(url = resp_url, json=json_data, verify=False, timeout=20)
        logging.info("|{} post success|".format(resp_url))
    except Exception as e:
        logging.error(traceback.format_exc())

def http_post(resp_url, json_data):
    threading.Thread(target=_http_post,args=(resp_url,json_data)).start()


if __name__ == "__main__":
    keeper = Keeper("serve/EDP/EDP_server.py",sh_file_path="/home/HwHiAiUser/traffic_paddle/serve/EDP/crontab_run.sh",stride_time=5)
    keeper.start()
    print("done")
    # keeper.close()